package com.nf.health.app.mine.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.RegisterBirthdayActivity;
import com.nf.health.app.activity.global.RegisterHeightActivity;
import com.nf.health.app.activity.global.RegisterNickActivity;
import com.nf.health.app.activity.global.RegisterWeightActivity;
import com.nf.health.app.core.DialogOnitem;
import com.nf.health.app.customview.BottomSslideDialog;
import com.nf.health.app.http.ImageUpLoader;
import com.nf.health.app.models.PersonalInfor;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.AppUtil;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.ImageUtils;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;

/**
 * @author Ian
 * @ClassName: PersonalInforActivity
 * @Description:个人资料页面
 * @date 2015-11-4 上午11:00:55
 */
public class PersonalInforActivity extends BaseActivity implements
        OnClickListener {

    private ImageView iv_icon;
    private UserInfo userInfo;
    private TextView zhenshiiv_nickName, iv_nickName, iv_sex, iv_height, iv_weight, iv_birthday,
            iv_illness, iv_nation;
    private RelativeLayout head_rl,zhenshi_nick_rl,nick_rl, sex_rl, height_rl, weight_rl,
            birthday_rl, history_rl, identity_rl, nation_rl;
    // 修改头像的请求码
//	public static final int IMAGE_REQUEST_CODE = 10;
//	public static final int CAMERA_REQUEST_CODE = 11;
//	public static final int RESULT_REQUEST_CODE = 12;
    private PersonalInfor result;
    private TextView iv_identity;
    private static final int PIC_CAMERA = 100;
    private static final int PIC_PHOTOS = 101;
    private static final int PIC_CUT = 103;

    String picTempPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_personal_infor);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "个人资料");
        iv_icon = (ImageView) findViewById(R.id.iv_icon);
        iv_nickName = (TextView) findViewById(R.id.iv_nickName);
        zhenshiiv_nickName = (TextView) findViewById(R.id.iv_zhenshinickName);
        iv_sex = (TextView) findViewById(R.id.iv_sex);
        iv_height = (TextView) findViewById(R.id.iv_height);
        iv_weight = (TextView) findViewById(R.id.iv_weight);
        iv_birthday = (TextView) findViewById(R.id.iv_birthday);
        iv_illness = (TextView) findViewById(R.id.iv_illness);
        iv_nation = (TextView) findViewById(R.id.iv_nation);
        iv_identity = (TextView) findViewById(R.id.iv_identity);
        head_rl = (RelativeLayout) findViewById(R.id.head_rl);
        nick_rl = (RelativeLayout) findViewById(R.id.nick_rl);
        zhenshi_nick_rl = (RelativeLayout) findViewById(R.id.zhenshi_nick_rl);
        sex_rl = (RelativeLayout) findViewById(R.id.sex_rl);
        height_rl = (RelativeLayout) findViewById(R.id.height_rl);
        weight_rl = (RelativeLayout) findViewById(R.id.weight_rl);
        birthday_rl = (RelativeLayout) findViewById(R.id.birthday_rl);
        history_rl = (RelativeLayout) findViewById(R.id.history_rl);
        identity_rl = (RelativeLayout) findViewById(R.id.identity_rl);
        nation_rl = (RelativeLayout) findViewById(R.id.nation_rl);
        userInfo = PreferenceHelper.getUser();
        initListener();
    }


    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    public void loadData() {
        provider.requestNewUserInfo("NEWUSERINFO");
    }

    private void initListener() {
        head_rl.setOnClickListener(this);
        nick_rl.setOnClickListener(this);
        sex_rl.setOnClickListener(this);
        height_rl.setOnClickListener(this);
        weight_rl.setOnClickListener(this);
        birthday_rl.setOnClickListener(this);
        history_rl.setOnClickListener(this);
        nation_rl.setOnClickListener(this);
        zhenshi_nick_rl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.history_rl:
                if (result != null) {
                    Bundle bundle1 = new Bundle();
                    bundle1.putString(Constants.INTENT_EXTRA_STRING, result.getSick_history());
                    ActivityUtils.showActivity(this, DiseaseKindsActivity.class, bundle1);
                }
                break;
            case R.id.head_rl:
                showBottomDialog();
                break;
            case R.id.nick_rl:
                Bundle bundle2 = new Bundle();
                bundle2.putInt("type", ModifyNickNameActivity.TYPE_MODIFY_NICKNAME);
                ActivityUtils.showActivity(this, ModifyNickNameActivity.class, bundle2);
                break;
            case R.id.identity_rl:
//                Bundle bundle3 = new Bundle();
//                bundle3.putInt("type", ModifyNickNameActivity.TYPE_MODIFY_IDENTIFY);
//                if (result != null) {
//                    bundle3.putString("value", result.getIdcard());
//                }
//                ActivityUtils.showActivity(this, ModifyNickNameActivity.class, bundle3);
                break;

            case R.id.sex_rl:
                Bundle bundle4 = new Bundle();
                bundle4.putString("type", "1");
                bundle4.putString("check_sex", iv_sex.getText().toString());
                ActivityUtils.showActivity(this, RegisterNickActivity.class, bundle4);
                break;
            case R.id.height_rl:
                Bundle bundle5 = new Bundle();
                bundle5.putString("type", "1");
                if (result != null) {
                    double doubleH = Double.parseDouble(result.getHeight());
                    int height = (int) doubleH;
                    bundle5.putInt("value", height);
                }
                ActivityUtils.showActivity(this, RegisterHeightActivity.class, bundle5);
                break;
            case R.id.weight_rl:
                Bundle bundle6 = new Bundle();
                bundle6.putString("type", "1");
                if (result != null) {
                    double doubleW = Double.parseDouble(result.getWeight());
                    int weight = (int) doubleW;
                    bundle6.putInt("value", weight);
                }
                ActivityUtils.showActivity(this, RegisterWeightActivity.class, bundle6);
                break;
            case R.id.birthday_rl:
                Bundle bundle7 = new Bundle();
                bundle7.putString("type", "1");
                ActivityUtils.showActivity(this, RegisterBirthdayActivity.class, bundle7);
                break;
            case R.id.nation_rl://
                Bundle bundle8 = new Bundle();
                bundle8.putString("type", "1");
                ActivityUtils.showActivity(this, NationActivity.class, bundle8);
                break;
            case R.id.zhenshi_nick_rl://
                Bundle bundle9 = new Bundle();
                bundle9.putInt("type", ModifyNickNameActivity.TYPE_MODIFY_RNAME);
                bundle9.putString("value",zhenshiiv_nickName.getText().toString());
                ActivityUtils.showActivity(this, ModifyNickNameActivity.class, bundle9);
                break;
        }
        super.onClick(v);
    }

    @SuppressLint("NewApi")
    private void showBottomDialog() {
        final String[] reportArr = new String[]{"添加照片", "从相册选择", "照相"};
        new BottomSslideDialog(PersonalInforActivity.this, true, null,
                reportArr, new DialogOnitem() {
            @Override
            public void onItemClickListener(int position) {
                switch (position) {
                    case 0:
                        picTempPath = Constants.ImageCachePath + System.currentTimeMillis() + ".jpg";
                        AppUtil.takePicFromaLocal(PersonalInforActivity.this, PIC_PHOTOS);
                        break;
                    case 1:
                        picTempPath = Constants.ImageCachePath + System.currentTimeMillis() + ".jpg";
                        AppUtil.takePicFromCamera(PersonalInforActivity.this, PIC_CAMERA, new File(picTempPath));
                        break;
                    default:
                        break;
                }

            }
        }).create();
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (actionName.equals("NEWUSERINFO")) {
            result = (PersonalInfor) object;
            ImageLoaderUtils.getinstance(this).getImage(iv_icon, result.getHimg(), R.drawable.default_head);
            iv_nickName.setText(result.getNick());
            if (result.getSex().equals("1")) {
                iv_sex.setText("男");
            } else {
                iv_sex.setText("女");
            }
            String userName = result.getRname();
            if(!TextUtils.isEmpty(userName)){
                zhenshiiv_nickName.setText(userName);
            }else{
                zhenshiiv_nickName.setText("未填写" );
            }
            iv_height.setText(result.getHeight() + " cm");
            iv_weight.setText(result.getWeight() + " kg");
            iv_birthday.setText(result.getBirthday());

            //名族
            if (!TextUtils.isEmpty(result.getNational())) {
                iv_nation.setText(result.getNational());
            } else {
                iv_nation.setText("暂无数据");
            }
            //疾病史
            String history = result.getSick_history();
            if (!TextUtils.isEmpty(history)) {
                if (history.startsWith("{")) {//version2.7之后变为json格式
                    String value = JsonUtils.getKey2Value(history, "value");
                    String other = JsonUtils.getKey2Value(history, "other");
                    if (TextUtils.isEmpty(value + other)) {//value other 都没有
                        iv_illness.setText("暂无数据");
                    } else {
                        if (!TextUtils.isEmpty(other) && !TextUtils.isEmpty(value)) {//value other 都有
                            iv_illness.setText(value + "," + other);
                        } else if (!TextUtils.isEmpty(value)) {//value
                            iv_illness.setText(value);
                        } else {
                            iv_illness.setText(other);//只有other
                        }
                    }
                } else {
                    iv_illness.setText(result.getSick_history());
                }
            } else {
                iv_illness.setText("暂无数据");
            }
            String idCard = result.getIdcard();
            if (!TextUtils.isEmpty(idCard)) {
                if (idCard.length() < 15) {
                    iv_identity.setText("格式错误");
                } else {
//                    iv_identity.setText(idCard.substring(0, 4) + "********" + idCard.substring(idCard.length() - 4, idCard.length()));
                    iv_identity.setText(idCard);
                }
            } else {
                iv_identity.setText("暂无数据");
            }
            PreferenceHelper.putString(PreferenceHelper.USERNICK, result.getNick());
            PreferenceHelper.putString(PreferenceHelper.USERSEX, result.getSex());
            PreferenceHelper.putString(PreferenceHelper.USERHEIGHT, result.getHeight() + "");
            //更新本地用户头像,使得医生聊天端能及时更新
            userInfo.setHimg(result.getHimg());
            userInfo.setRname(userName);
            userInfo.setHeight(result.getHeight() + "");
            userInfo.setSex(result.getSex());
            userInfo.setWeight(result.getWeight() + "");
            userInfo.setBirthday(result.getBirthday() + "");
            userInfo.setUserid(result.getUserid() + "");
            if(!TextUtils.isEmpty(userName)){
                userInfo.setUserid(result.getUserid() + "");
                PreferenceHelper.putString(PreferenceHelper.USERRNAME, result.getRname());
            }
            PreferenceHelper.putUser(userInfo);

        } else if ("uploadImage".equals(actionName)) {
            Log.v("tag", "uploadImage:" + object);
            String url = "" + object;
            if (url != null) {
                if (userInfo != null) {
                    userInfo.setHimg(url);
                }
                provider.requestSaveHeader(url, "requestSaveHeader");

                iv_icon.setTag(url);
                ImageLoaderUtils.getinstance(this).getImage(iv_icon, url, R.drawable.default_head);
            }
        } else if ("requestSaveHeader".equals(actionName)) {
            showToast("保存成功");
            // PreferenceHelper.putString("headerUrl", iv_icon.getTag() + "");//
            PreferenceHelper.putString(PreferenceHelper.USERICON, iv_icon.getTag().toString());// 更新本地图片
            loadData();

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PIC_CAMERA:
                    // ToastUtil.showShortToast(this, "临时图片路径：" + Uri.fromFile(tempFile));
//				 Toast.makeText(this,"临时图片路径：" + Uri.fromFile(tempFile),0).show();
                    // 拿到照片的uri，继续调用系统的剪裁
                    ImageUtils.startPhotoZoom(this, Uri.fromFile(new File(picTempPath)), PIC_CUT, true);
                    break;
                case PIC_PHOTOS:
                    if (data != null) {
                        ImageUtils.startPhotoZoom(this, data.getData(), PIC_CUT, false);
                    }
                    break;
                case PIC_CUT:
                    // 剪裁完的图片设置到imageView上
                    if (data != null) {
                        //Bundle bundle = data.getExtras();
                        //final Bitmap bitmap = bundle.getParcelable("data");

                        //将Uri图片转换为Bitmap
                        Bitmap bitmap = null;
                        try {
                            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(ImageUtils.uritempFile));
                            if (bitmap != null) {
                                boolean saveImage = ImageUtils.saveImage(bitmap, picTempPath);
                                if (saveImage) {
                                    uploadPic();
                                }
                            }
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
            }
        }
    }

    private void uploadPic() {
        ImageUpLoader upLoader = new ImageUpLoader(PersonalInforActivity.this, PersonalInforActivity.this);
        upLoader.uploadImage(new File(picTempPath), new HashMap<String, String>());//
    }
}
